package com.miya.demo.common.util;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.miya.demo.common.enums.IDPrefixEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * id工具类
 *
 * @author Caixiaowei
 * @date 2022/06/15
 */
@Slf4j
@Component
public class IdUtil {

    @Autowired
    private static RedisTemplate<String, String> redisTemplate;

    public IdUtil(RedisTemplate<String, String> redisTemplate) {
        IdUtil.redisTemplate = redisTemplate;
    }

    public static String generator(IDPrefixEnum idPrefixEnum) {
        // 业务code
        String prefix = idPrefixEnum.getPrefix();
        // 年月日
        String yyyyMMdd = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyyMMdd");
        // 当日ID:key
        String key = prefix  + yyyyMMdd;
        Long increment = Long.valueOf(redisTemplate.opsForValue().increment(key));
        return key + String.format("%0" + idPrefixEnum.getLength() +"d", increment);
    }

}
